<template>
	<view style="background-color: #F2F2F5;" v-if="showadd()">
		<view class="main">
			<u-modal :show="show" title="确定删除这条记录吗" :showCancelButton="true"   @confirm="confirm" @cancel="cancel"></u-modal>

			<view>
				<u-line-progress :percentage=percentage height="20" inactiveColor="#F2F2F5"  activeColor="#FF4D88"></u-line-progress>
			</view>
			<view class="pubcontent">
                 <textarea   auto-height  v-model="content" placeholder-style="color:#F76260" placeholder="写点什么.."/>
			</view>
			<view class="editpicture">
				<u-upload width="204rpx" height="225rpx" :fileList="fileList1" @afterRead="afterRead"
					@delete="deletePic" name="1" multiple :maxCount="9"></u-upload>
			</view>
			<view class="edittime">
				<view class="textarea" style="flex: 1;padding: 15rpx; ">
					<uni-icons type="redo" size="22" style=" vertical-align: middle;">
					</uni-icons>
					<text>记录时间</text>
				</view>
				<view class="timearea" style="flex: 1;text-align: end; padding: 15rpx;" @click="opendatepop()">
					<text style="white-space: nowrap; overflow: hidden;">{{pubtime}}</text>
					<uni-icons type="arrow-right" size="22" style="vertical-align:text-bottom;color: red;">
					</uni-icons>
				</view>

			</view>
			
			<view class="savebutton">
				<button @click="pub" class="mini-btn" size="default" type="warn">保存</button>
			</view>
			
			<view class="delbutton" v-if="optype=='edit'" @click="del">
				<text>删除这条记录</text>
			</view>
			
			<choicedate :selectedDate="dischargeTime" @dateSelected="setDischargeTime" @popType="datesPopFunc" v-if="datesPop" />
			
			<!-- // 时间组件 传递参数
			@dateSelected=  子组件emit的事件 子传父
			:selectedDate  父传子
			// dischargeTime  选中时间：String类型，如为空则选择当日
			// setDischargeTime 设置选中时间： func类型，改变选中值显示到页面的函数
			// datesPopFunc 改变 v-if 的函数 -->
			
		</view>


	</view>

</template>

<script>
	import * as utils from '../../util/util.js';
	
	export default {
		data() {
			return {
				show:false,
				id:"",
				percentage:"0", //进度条
				complete:0,//
				optype:"add", //添加还是编辑
				content: '',
				dischargeTime:'',//选择的空间 yyyy-mm-dd
				pubtime:'',
				datesPop:false, //时间弹层控制
				fileList1: [
					// {
					// url: "https://mp-4ef949ae-9caf-46af-aeb8-85d88c12ee81.cdn.bspapp.com/cloudstorage/f2ea08fb-4d32-4544-aeae-8d8854fd30ac.jpg",
					// },
				],
				editpicurl:[]
			}
		},
		onLoad(option) {
			//编辑
			if(option.type=='edit'){
				console.log("编辑"+option.id)
				this.id = option.id;
				let _this = this;
				this.optype = 'edit'
				utils.getListById(option.id).then(res=>{
					const data = res.result.data[0];
					_this.content = data.content;
					const arr = data.url.map(item=>{
						return {
							url:item
						}
					})
					_this.editpicurl = data.url;
					_this.fileList1.push(...arr);
					_this.pubtime = data.recordtime.replace(/(\d{4})\-(\d{2})\-(\d{2})/,"$1年$2月$3日");
					_this.dischargeTime = data.recordtime;
				})
				return;
			}
			this.pubtime = utils.formatDate(new Date());
			this.dischargeTime = utils.formatDateyyymmdd(new Date());
		},
		methods: {
			del(){
				this.show = true;
			},
			showadd(){
				return utils.show();
			},
			
			confirm() {
				var _this = this;
				uniCloud.callFunction({
					name:"delpublish",
					data:{
						id:_this.id
					}
				}).then(res=>{
					uni.reLaunch({
						url:'/pages/index/index'
					})
				}).catch(er=>{
					console.log(er);
					utils.toastwarn("删除失败"+er)
				})
				
			},
			cancel(){
				this.show = false;
			},
			
			opendatepop(){
				this.datesPop = true;
			},
			setDischargeTime(date){
				console.log(date);
				let arr = date.split('-');
				this.pubtime = arr[0]+'年'+arr[1]+'月'+arr[2]+'日';
				this.datesPop = false;
				this.dischargeTime = date;
			},
			datesPopFunc(){
				this.datesPop = false;
			},
			
			pub() {
				var that = this;
				let complete = 0;
				if(this.fileList1.length == 0||this.content.trim().length==0){
					utils.toastwarn("请选择一张图片和填写内容",1000);
					return;
				}
				uni.showLoading({"title":"处理中","mask":true});
				if(this.optype=='add'){
					//进度条
					const asyncTask = utils.uploadFiles(this.fileList1);
					for (let i = 0; i < asyncTask.length; i++) {
						asyncTask[i].then( function(res){
							 that.complete++;
							 that.percentage = (that.complete * 100) / that.fileList1.length;
						},reason=>{
							utils.toastwarn("保存失败",1000);
						});
					}
					
					//等待所有完成
					Promise.all(asyncTask).then(results => {					
							const picurl = results.map(item =>{ return item.fileID});
							console.log(picurl);
							let para = {
								 "username":utils.getLoginInfo().username,
								 "userid": utils.getLoginInfo().id,
								 "content": that.content,
								 "recordtime":that.dischargeTime,
								 "createtime":Date.now(),
								 "url":picurl,
								 type:'img'
							 };
							 console.log(para);
							 utils.addpublish(para).then(res=>{
								 uni.hideLoading();
								 uni.reLaunch({
								 	url:'/pages/index/index'
								 })
							 }).catch(error=>{
								 utils.toastwarn("上传出错",1000);
							 })
					}).catch(error => {
					    console.error('An async task failed:', error);
						utils.toastwarn("上传出错",1000);
					});
				}else{
					const current = this.fileList1.map(item=>{return item.url});
					const upload = current.filter(item=>!this.editpicurl.includes(item));
					let para = {
						 "id":that.id,
						 "content": that.content,
						 "recordtime":that.dischargeTime,
						 "url":current
					 };
					if(upload.length == 0){
						utils.editpublish(para).then(res=>{
							 uni.hideLoading();
							 uni.reLaunch({
							 	url:'/pages/index/index'
							 })
						}).catch(er=>{
							 utils.toastwarn("更新出错",1000);
						})
						return;
					}
					//上传就行了
					const asyncTask = utils.uploadFiles(upload.map(item=>{
						return {'url':item}
					}));
					
					for (let i = 0; i < asyncTask.length; i++) {
						asyncTask[i].then( function(res){
							 that.complete++;
							 that.percentage = (that.complete * 100) / upload.length;
						},reason=>{
							utils.toastwarn("保存失败",1000);
						});
					}
					
					//等待所有完成
					Promise.all(asyncTask).then(results => {
							console.log(results);
							const map = {};
							results.forEach(item=>{
								map[item.filePath] = item.fileID;
							})
							console.log(map);
							const picurlold = that.fileList1.map(item=>{return item.url});
							console.log(picurlold);
							
							const uploadarr = picurlold.map(item=>{
								if(map[item]){
									return map[item];
								}
								return item;
							})
							para.url = uploadarr;
							utils.editpublish(para).then(res=>{
								 uni.hideLoading();
								 uni.reLaunch({
								 	url:'/pages/index/index'
								 })
							}).catch(er=>{
								 utils.toastwarn("更新出错",1000);
							})
					}).catch(error => {
					    console.error('An async task failed:', error);
						utils.toastwarn("更新出错",1000);
					});
					
					
					
					
				}
				//编辑
			},

			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
				console.log(this.fileList1.length);
				this.fileList1.map((file, index) => {
					console.log(index, file.url);
				})
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length

				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'pending',
						message: ''
					})
				})
			},

			
		}

	}
</script>

<style lang="scss" scoped>
	.main {
		display: flex;
		flex-direction: column;
		background-color: #F2F2F5;
		padding: 25rpx;

		.u-upload__wrap {
			padding: 10rpx;
		}

		.u-border {
			display: inline-block;
			border-style: none !important;
			border: none !important;
			padding: 0;
			margin: 0;
			background: transparent !important;
		}
		
		.u-border::after {
			border: none !important;
		}
	}

	.pubcontent {
		width: 700rpx;
		height: 200rpx;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		background-color: white;
		margin-top: 25rpx;
	}

	.editpicture {
		background-color: white;
		padding: 20rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		width: 700rpx;
	}

	.edittime {
		width: 700rpx;
		display: flex;
		background-color: white;
		border-top: 1rpx solid #F2F2F5;
	}

	.savebutton {
		margin-top: 50rpx;

		button {
			display: block;
			//margin: 0 auto;
			background-color: #FF4D88;
			border-radius: 50rpx;
			height: 100rpx;
			font-weight: bold;
		}
	}
	
	.delbutton{
		margin-top: 50rpx;
		display: flex;
		justify-content: center;
		font-weight: bold;
		text{
			color: #FF4D88;
		}
	}
</style>